package com.dpad.telematicsclientapp.presenter

import android.content.Intent

import com.alibaba.android.arouter.launcher.ARouter
import com.dpad.telematicsclientapp.mvp.mvp.XPresent
import com.alibaba.fastjson.JSON
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption

import com.dpad.telematicsclientapp.netlibrary.newapp.entity.CardItem3
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.YckzZipEntity
import com.dpad.telematicsclientapp.mvp.kit.Kits
import com.dpad.telematicsclientapp.netlibrary.Contances
import com.dpad.telematicsclientapp.netlibrary.MainApplicaton
import com.dpad.telematicsclientapp.netlibrary.http.NetInstance
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.LoginBean
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.SplashBean2
import com.dpad.telematicsclientapp.ui.SplashActivity
import com.dpad.telematicsclientapp.util.DataStatisticsUtils
import com.dpad.telematicsclientapp.util.PreferenceUtils
import com.dpad.telematicsclientapp.util.TitleToCode
import com.dpad.telematicsclientapp.util.utils.Constant
import com.dpad.telematicsclientapp.util.utils.ParameterUtils
import com.dpad.telematicsclientapp.utils.RegisterClientIdUtils
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.io.IOException
import java.util.*

/**
 * ================================================
 * 作    者：wenbody
 * 版    本：1.0
 * 创建日期：2019/12/17 15:42
 * 描    述：
 * 修订历史：
 * ================================================
 */
class SplashPresenter : XPresent<SplashActivity>() {

    //声明AMapLocationClient类对象
    lateinit var mLocationClient: AMapLocationClient


     fun tokenLogin() {
         if (Kits.Empty.check(PreferenceUtils.getInstance(v.mContext()).getString("USERNAME"))) {
            getSplashActivity()
            return
        }
        val sortedMap: SortedMap<String, Any> = TreeMap()
        sortedMap["userName"] = PreferenceUtils.getInstance(v.mContext()).getString("USERNAME")
        //统计登录
               NetInstance.getEventsService()
                .tokenLogin(ParameterUtils.getHeaser(sortedMap), ParameterUtils.getJsonBody(sortedMap))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<LoginBean> {
                    override fun onSubscribe(d: Disposable) {
                        addDisposable(d)
                    }

                    override fun onNext(loginBean: LoginBean) {
                        if (loginBean.code == "00000") {
                            MainApplicaton.LOGINRESULTVO.token = loginBean.result.token
                            MainApplicaton.LOGINRESULTVO.userName = loginBean.result.userName
                            MainApplicaton.LOGINRESULTVO.userId = loginBean.result.userId
                            MainApplicaton.LOGINRESULTVO.isAgree = loginBean.result.isAgree
                            MainApplicaton.LOGINRESULTVO.nickName = loginBean.result.nickName
                            /**
                             * 注册clientId
                             */
                            if (!Kits.Empty.check(MainApplicaton.clientId)) {
                                RegisterClientIdUtils.bindingClient(MainApplicaton.clientId)
                            }
                            PreferenceUtils.getInstance(v.mContext()).setString("USERNAME", loginBean.result.userName)
                            PreferenceUtils.getInstance(v.mContext()).setString(Constant.USERID_KEY, loginBean.result.userId)
                            PreferenceUtils.getInstance(v.mContext()).setString(Constant.LOGIN_NAME, loginBean.result.userName)
                            PreferenceUtils.getInstance(v.mContext()).setString("TOKEN", loginBean.result.token)
                            PreferenceUtils.getInstance(v.mContext()).setString("isAgree", loginBean.result.isAgree)
                            PreferenceUtils.getInstance(v.mContext()).setString(Constant.LOGIN_NICKNAME, loginBean.result.nickName)
                            PreferenceUtils.getInstance(v.mContext()).setString(Constant.LOGIN_USERPIC, loginBean.result.picUrl)
                            MainApplicaton.sIsLogin = true
                            MainApplicaton.setVin(if (Kits.Empty.check(loginBean.result.vin)) "" else loginBean.result.vin)
                            MainApplicaton.isTcar = !Kits.Empty.check(loginBean.result.isTServer) && loginBean.result.isTServer == "1"
                            MainApplicaton.setUserVehType(loginBean.result.userVehType)
                            MainApplicaton.setBurialPointUserType(loginBean.result.burialPointUserType)
                            MainApplicaton.setSaleSubmodelId(loginBean.result.saleSubmodeId)
//                            Log.e("AAAAA","token登录时的车型为"+loginBean.result.saleSubmodeId)
                            if (Kits.Empty.check(loginBean.result.saleSubmodeId)) {
                                getSplashActivity()
                            } else {
                                setPicUrl()
                            }
                            DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE142.title, System.currentTimeMillis().toString(), Constant.NOMAL));
                        } else {
                            jumpToHome()
//                            jumpToLoginActivity()
                        }

                    }

                    override fun onError(e: Throwable) {
                        v.loadingComplete()
                        v.dealHttpError(e)
                        jumpToHome()
//                        jumpToLoginActivity()
                    }

                    override fun onComplete() {
                        v.loadingComplete()
                    }
                })
    }

    fun getSplashActivity() {
        val cityCode= PreferenceUtils.getInstance(v.mContext()).getString("cityCode")
        val sortedMap: SortedMap<String?, Any?> = TreeMap<String, Any?>()
        sortedMap["cityCode"] =cityCode
        NetInstance.getEventsService().getSplashActivity(ParameterUtils.getHeaser(sortedMap), ParameterUtils.getJsonBody(sortedMap))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<SplashBean2> {
                    override fun onSubscribe(d: Disposable) {
                        addDisposable(d)
                    }

                    override fun onNext(bean: SplashBean2) {
                        if (bean.code == "00000") {
                            v.showSplash(bean)
                        } else {
                            jumpToHome()
                        }
                    }

                    override fun onError(e: Throwable) {
                        v.loadingComplete()
                        v.dealHttpError(e)
                        jumpToHome()
                    }

                    override fun onComplete() {
                        v.loadingComplete()
                    }
                })
    }




    fun jumpToHome() {
        //添加游客或者非t车
        if (MainApplicaton.userVehType == "0" || MainApplicaton.userVehType == "4") {//游客或者非t车 直接跳转
            goToHomeActivity(true)
        } else {
            if (MainApplicaton.isTcar) {//有t车
                goToHomeActivity(true)
            } else {//t车未激活,跳转到激活页面
                selectjihuo()
            }
        }
//        val intent = Intent(v.mContext(), HomeActivity::class.java)
//        v.mContext().startActivity(intent)
//        v.mContext().finish()
    }
    private fun goToHomeActivity(isLoginSuccess: Boolean) {
//        val intent = Intent(v.mContext(), HomeActivity::class.java)
//        intent.putExtra("loginStatus", isLoginSuccess)
//        v.mContext().startActivity(intent)


        ARouter.getInstance()
                .build(Contances.URL_ACTIVITY_HOME, Contances.GROUP_HOME)
                .withBoolean("loginStatus",isLoginSuccess)
                .navigation(v.mContext())

        v.mContext().finish()
    }
    private fun jumpToLoginActivity() {
//        val intent = Intent(v.mContext(), KtLoginActivity::class.java)
//        v.mContext().startActivity(intent)

        ARouter.getInstance()
                .build(Contances.URL_ACTIVITY_LOGIN, Contances.GROUP_LOGIN)
                .navigation(v.mContext())

        v.mContext().finish()

    }

    fun selectjihuo() {
        v.loading("正在加载...")
        val sortedMap: SortedMap<String, Any> = TreeMap<String, Any>()
        sortedMap["userId"] = MainApplicaton.LOGINRESULTVO.userId
        sortedMap["vin"] = MainApplicaton.vin
        NetInstance.getEventsService()
                .tjihuo3(ParameterUtils.getHeaser(sortedMap), ParameterUtils.getJsonBody(sortedMap))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<CardItem3> {
                    override fun onSubscribe(d: Disposable) {
                        addDisposable(d)
                    }

                    override fun onNext(bean: CardItem3) {
                        if (bean.code == "00000") {
                            v.showListViewData(bean.result)
                        }
                    }

                    override fun onError(e: Throwable) {
                        v.loadingComplete()
                        v.dealHttpError(e)
                    }

                    override fun onComplete() {
                        v.loadingComplete()
                    }
                })
    }

    //获取全局的图片地址
    fun setPicUrl() {
//        populevehicle 我的爱车车图
//        uservehicle 个人中心车图
//        ecovehicle 环保驾驶车图
//        indexvehicleinfo 首页车况报告车图
//        vehicleinfoblue 车况报告车图蓝底
//        vehicleinfored 车况报告车图红底
//        vehicleinfoyellow 车况报告车图黄底

        v.loading("正在加载...")
        val sortedMap: SortedMap<String?, Any?> = TreeMap<String?, Any?>()
        sortedMap["saleSubmodelId"] = MainApplicaton.getSaleSubmodelId()
        sortedMap["downloadType"] = "1" //0为zip 1为车型图片 2为远控图片
        NetInstance.getEventsService().picDownload(ParameterUtils.getHeaser(sortedMap), ParameterUtils.getJsonBody(sortedMap))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<YckzZipEntity> {
                    override fun onSubscribe(d: Disposable) {
                        addDisposable(d)
                    }

                    override fun onNext(bean: YckzZipEntity) {
                        if (bean.code == "00000") {
                            MainApplicaton.urlMap.clear()
                            if (!bean.result.isNullOrEmpty()) {
                                for (item in bean.result) {
                                    if (!Kits.Empty.check(item.mark)) {
                                        when (item.mark) {
                                            "populevehicle" -> {
                                                MainApplicaton.urlMap["populevehicle"] = item.downloadPath
                                            }
                                            "uservehicle" -> {
                                                MainApplicaton.urlMap["uservehicle"] = item.downloadPath
                                            }
                                            "ecovehicle" -> {
                                                MainApplicaton.urlMap["ecovehicle"] = item.downloadPath
                                            }
                                            "indexvehicleinfo" -> {
                                                MainApplicaton.urlMap["indexvehicleinfo"] = item.downloadPath
                                            }
                                            "vehicleinfoblue" -> {
                                                MainApplicaton.urlMap["vehicleinfoblue"] = item.downloadPath
                                            }
                                            "vehicleinfored" -> {
                                                MainApplicaton.urlMap["vehicleinfored"] = item.downloadPath
                                            }
                                            "vehicleinfoyellow" -> {
                                                MainApplicaton.urlMap["vehicleinfoyellow"] = item.downloadPath
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        getSplashActivity()
                    }

                    override fun onError(e: Throwable) {
                        v.loadingComplete()
                        v.dealHttpError(e)
                        getSplashActivity()
                    }

                    override fun onComplete() {
                        v.loadingComplete()
                    }
                })
    }

}